package ar.edu.uba.fi.jmit.monitorengine;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;

public class FileUtils {
	
	private static Logger logger = Logger.getLogger(FileUtils.class);

	public static String getFilePath(String fileName) throws FileNotFoundException {
		logger.debug("Looking for file " + fileName);
		URL url = findFileAsResource(fileName);
		if(url != null) {
			if(logger.isDebugEnabled()) {
				logger.debug("Founded file path: " + url.getFile());
			}
			return url.getFile();
		}
		logger.info("File for name " + fileName + " not found");
		logger.info("Path of . " + findFileAsResource("."));
		throw new FileNotFoundException("Cound not find file for name " + fileName + " in any of the known locations.");
	}
	
	public static URL findFileAsResource(String filePath) throws FileNotFoundException {
		logger.debug("looking for file " + filePath);
		File file = new File(filePath);
		if(file != null && file.exists()) {
			try {
				logger.debug(filePath + " was found as a file");
				return file.toURI().toURL();
			} catch (MalformedURLException e) {
				throw new RuntimeException(e);
			}
		}
		URL url = ClassLoader.getSystemClassLoader().getResource(filePath);
		if(url != null) {
			logger.debug(filePath + " was found with the system classloader");
			return url;
		}
		url = FileUtils.class.getClassLoader().getResource(filePath);
		if(url != null) {
			logger.debug(filePath + " was found with the actual class classloader");
			return url;
		}
		if (filePath.startsWith("./")) {
			return findFileAsResource(filePath.substring(2));
		}
		throw new FileNotFoundException("File could not be found on standard locations " + filePath);
	}
}
